<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label>
            <ASelect
              v-model="searchFrom.productId"
              placeholder="产品名称"
              allow-clear
              :trigger-props="{ contentStyle: { width: 'max-content' } }"
              allow-search
            >
              <AOption
                v-for="(item, index) in productList"
                :key="index"
                :label="item.productName"
                :value="item.productId"
              >
                <div class="w100 erp-row-center-between">
                  <div>{{ item.productName }}</div>
                  <ATag v-if="item.specModel" color="blue">
                    {{ item.specModel }}
                  </ATag>
                </div>
              </AOption>
            </ASelect>
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.prodFlowCode" placeholder="生产完成编号" allow-clear />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <ATooltip
            v-if="isAuth([1, 2])"
            content="请选择未入库的数据"
            :disabled="!(isEmpty(selectRows) || !!selectRows.find((item) => item.inboundStatus))"
          >
            <AButton
              type="outline"
              :disabled="isEmpty(selectRows) || !!selectRows.find((item) => item.inboundStatus)"
              :loading="inWarehouseLoad"
              @click="inWarehouse()"
            >
              入库
            </AButton>
          </ATooltip>
          <ATooltip v-if="isAuth([1, 2])" :disabled="!isEmpty(selectRows)" content="请选择数据">
            <AButton status="danger" @click="batchDel()">批量删除</AButton>
          </ATooltip>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :row-selection="{ showCheckedAll: true, type: 'checkbox' }"
        :span-method="spanMethod"
        span-all
        column-resizable
        size="small"
        row-key="prodFlowDetialId"
        @select="
          (rowKeys: (string | number)[], rowKey: string | number, record: TableData) =>
            tableEvent('select', { rowKeys, rowKey, record })
        "
        @select-all="(checked: boolean) => tableEvent('select-all', checked)"
      >
        <template #columns>
          <ATableColumn title="创建日期" data-index="createdDt" :width="100">
            <template #cell="{ record }">
              <div>{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="生产完成单" data-index="prodFlowCode" :width="100">
            <template #cell="{ record }">
              {{ record.prodFlowCode }}
            </template>
          </ATableColumn>
          <ATableColumn title="生产计划单" data-index="prodPlanCode" :width="100">
            <template #cell="{ record }">
              {{ record.prodPlanCode }}
            </template>
          </ATableColumn>
          <ATableColumn title="产品名称" data-index="productName" :width="100"></ATableColumn>
          <ATableColumn title="规格型号" data-index="specModel" :width="100"></ATableColumn>
          <ATableColumn title="单位" data-index="unit" :width="100"></ATableColumn>
          <ATableColumn title="工序" data-index="processName" :width="100"></ATableColumn>
          <ATableColumn title="机长" data-index="mainDirectorName" :width="100"></ATableColumn>
          <ATableColumn title="辅助人员" data-index="" :width="100">
            <template #cell="{ record }">
              <div v-if="record.deputyDirectorNameList">
                {{ record.deputyDirectorNameList.join(',') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="数量" data-index="qty" :width="100"></ATableColumn>
          <ATableColumn title="损耗率" data-index="lossRate" :width="100">
            <template #cell="{ record }">
              <div v-if="record.lossRate">{{ `${record.lossRate}%` }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="成品数量" data-index="productQty" :width="100"></ATableColumn>
          <ATableColumn title="总损耗率" data-index="totalLossRate" :width="100">
            <template #cell="{ record }">
              <div v-if="record.totalLossRate">{{ `${record.totalLossRate}%` }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="入库" data-index="inboundStatus" :width="80" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill
                v-if="record.inboundStatus"
                style="color: #67c23a"
                size="20px"
              />
              <icon-close-circle-fill v-if="!record.inboundStatus" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="100"></ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="150" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import { Message, Modal, TableData, TableInstance } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  batchDelProdFinish,
  delProFinish,
  getProFinishAllList,
  getProFinishPageList,
  productInWarehouse,
  ProductionFinishListSearch,
  ProductionFinishResItem,
  ProductionInWarehouseReq
} from '@renderer/api/productionDep'
import { getProductAllList, ProductResItem } from '@renderer/api/salesDep'
import { isEmpty } from 'lodash-es'
import dayjs from 'dayjs'

const searchFrom = ref<ProductionFinishListSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<ProductionFinishResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const productList = ref<ProductResItem[]>([])
const selectRows = ref<any[]>([])
const inWarehouseLoad = ref(false)
const tableRef = ref<TableInstance>()

const getProductList = async () => {
  const res = await getProductAllList({})
  productList.value = res.data.list
}

onMounted(() => {
  getProductList()
  getTableData()
})

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectRows.value = []
}

function batchDel() {
  const idList = selectRows.value.map((item) => item.prodFlowId)
  batchDelProdFinish({ idList: idList }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

function formatData(baseData: ProductionFinishResItem[]) {
  return baseData
    .map((item) => {
      if (!isEmpty(item.detailList)) {
        return item.detailList.reverse().map((detailItem, index) => {
          if (index === 0) {
            return { ...detailItem, ...item, span: item.detailList.length }
          } else {
            return { ...detailItem, ...item }
          }
        })
      } else {
        return [item]
      }
    })
    .flat()
}

async function getTableData() {
  const res = await getProFinishPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = formatData(res.data.list)
  pageParam.totalCount = res.data.totalCount!
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 7 || columnIndex > 11) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function tableEvent(type: 'page-change' | 'select' | 'select-all', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break
    case 'select':
      {
        const { rowKeys, rowKey, record } = param
        if (rowKeys.includes(rowKey)) {
          selectRows.value.push(record)
          // 判断是否全选
          const tempIDs = selectRows.value.map((item) => item.prodFlowDetialId)
          if (tableData.value.every((item) => tempIDs.includes(item.prodFlowDetialId))) {
            tableRef.value?.selectAll(true)
          }
        } else {
          selectRows.value = selectRows.value.filter(
            (item) => item.prodFlowDetialId != record.prodFlowDetialId
          )
        }
      }
      break
    case 'select-all':
      if (param) {
        selectRows.value = selectRows.value.concat(tableData.value)
      } else {
        const ids = tableData.value.map((item) => item.prodFlowDetialId)
        selectRows.value = selectRows.value.filter((item) => !ids.includes(item.prodFlowDetialId))
      }
      break

    default:
      break
  }
}

const inWarehouse = () => {
  if (isEmpty(selectRows.value)) return
  Modal.warning({
    title: '提醒',
    content: '是否确认入库',
    okText: '确认',
    cancelText: '取消',
    simple: false,
    hideCancel: false,
    maskClosable: false,
    closable: false,
    onOk: () => {
      inWarehouseLoad.value = true
      const params: ProductionInWarehouseReq[] = selectRows.value.map((item) => {
        return {
          materialName: item.productName,
          spec: item.specModel,
          stockQty: item.productQty,
          prodFlowId: item.prodFlowId
        }
      })
      productInWarehouse(params)
        .then(() => {
          Message.success('入库成功')
          getTableData()
          clearTableSelect()
        })
        .finally(() => {
          inWarehouseLoad.value = false
        })
    },
    onCancel: () => {}
  })
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})

function rowEvent(row: ProductionFinishResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delProFinish({ prodFlowId: row.prodFlowId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break

    default:
      break
  }
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '创建日期', value: 'createdDt', width: 180 },
    { title: '生产完成单', value: 'prodFlowCode', width: 180 },
    { title: '生产计划单', value: 'prodPlanCode', width: 180 },
    { title: '产品名称', value: 'productName', width: 180 },
    { title: '规格型号', value: 'specModel', width: 180 },
    { title: '单位', value: 'unit' },
    { title: '工序', value: 'processName' },
    { title: '机长', value: 'mainDirectorName' },
    { title: '辅助人员', value: 'deputyDirectorNames' },
    { title: '数量', value: 'qty' },
    { title: '损耗率', value: 'lossRate' },
    { title: '成品数量', value: 'productQty' },
    { title: '总损耗率', value: 'totalLossRate' },
    { title: '入库', value: 'inboundStatus' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: ProductionFinishResItem[] = []
  const merges: string[] = []
  switch (type) {
    case 'table':
      {
        let mergerIndex = 2
        fileTitle = '生产完成数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getProFinishAllList(searchFrom.value)
        excelData = formatData(res.data.list)
        excelData = excelData.map((item, index) => {
          item.index = index + 1
          item.createdDt = item.createdDt ? dayjs(item.createdDt).format('YYYY-MM-DD') : ''
          item.inboundStatus = item.inboundStatus ? '是' : '否'
          item.deputyDirectorNames = item.deputyDirectorNameList?.join(',')
          if (item.span) {
            merges.push(`B${mergerIndex}:B${mergerIndex + item.span - 1}`)
            merges.push(`C${mergerIndex}:C${mergerIndex + item.span - 1}`)
            merges.push(`D${mergerIndex}:D${mergerIndex + item.span - 1}`)
            merges.push(`E${mergerIndex}:E${mergerIndex + item.span - 1}`)
            merges.push(`F${mergerIndex}:F${mergerIndex + item.span - 1}`)
            merges.push(`G${mergerIndex}:G${mergerIndex + item.span - 1}`)
            merges.push(`M${mergerIndex}:M${mergerIndex + item.span - 1}`)
            merges.push(`N${mergerIndex}:N${mergerIndex + item.span - 1}`)
            merges.push(`O${mergerIndex}:O${mergerIndex + item.span - 1}`)
            merges.push(`P${mergerIndex}:P${mergerIndex + item.span - 1}`)
          }
          mergerIndex += item.span ? item.span : 0
          return item
        })
        console.log(excelData)
      }
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle, { merges: merges })
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
